package com.example.springboot_system.Controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.springboot_system.pojo.User;
import com.example.springboot_system.pojo.vo.register.RegisterInforReqVO;
import com.example.springboot_system.service.MedicalExaminationService;
import com.example.springboot_system.service.PayService;
import com.example.springboot_system.service.RegisterService;
import com.example.springboot_system.utils.AlipayConfigQRCode;
import com.example.springboot_system.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@Controller
public class PayController {
    public static String trade_noCheck =null;//这些全局变量用于判断沙箱支付是否成功
    public static String registerIdCheck =null;
    public static String cardId1 =null;
    public static String prescriptionNum1 =null;
    public static RegisterInforReqVO  vo = new RegisterInforReqVO();

    @Autowired
    private PayService payService;

    @Autowired
    private RegisterService registerService;

    @Autowired
    private MedicalExaminationService medicalExaminationService;

    @RequestMapping("/CheckToPay")
    @ResponseBody
    public ResponseResult CheckToPay(String prescriptionNum,
                                     HttpSession session){
        ResponseResult result = payService.CheckToPay(prescriptionNum, session);
        return result;
    }

    @RequestMapping("/MoneyToPay")
    @ResponseBody
    public ResponseResult MoneyToPay(String cardId, String prescriptionNum,
                                      HttpSession session){
        ResponseResult result = payService.MoneyPay(cardId, prescriptionNum, session);
        return result;
    }

    //诊单的支付宝支付
    @RequestMapping("/AlipayToPay")
    @ResponseBody
    public String toPay(String totalPrice,String cardId,
                        String prescriptionNum,String name,HttpServletResponse response) throws AlipayApiException, IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigQRCode.gatewayUrl,
                AlipayConfigQRCode.app_id,
                AlipayConfigQRCode.merchant_private_key, "json",
                AlipayConfigQRCode.charset,
                AlipayConfigQRCode.alipay_public_key,
                AlipayConfigQRCode.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //这里设置支付后跳转的地址
        alipayRequest.setReturnUrl("http://localhost:8090/notify_url2");

        //付款金额，必填
        String total_amount = totalPrice;
        //订单名称，必填
        String subject = "病人名字："+name;

        //给全局变量赋值用于后面判断是否支付成功
        trade_noCheck =null;
        cardId1 =null;
        prescriptionNum1 =null;
        String id = UUID.randomUUID().toString();
        trade_noCheck =id;
        cardId1=cardId;
        prescriptionNum1=prescriptionNum;

        //订单编号
        String out_trade_no = id;
        //商品描述，可空
        String body = "处方号为 "+prescriptionNum;

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "5m";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        AlipayConfigQRCode.logResult(result);// 记录支付日志
        response.setContentType("text/html; charset=gbk");
        PrintWriter out = response.getWriter();
        out.print(result);

        return null;
    }

    //体检的支付宝支付
    @RequestMapping("/AlipayToPayExam")
    @ResponseBody
    public String AlipayToPayExam(String totalPrice,
                        String prescriptionNum,String name,String registerId,HttpServletResponse response) throws AlipayApiException, IOException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigQRCode.gatewayUrl,
                AlipayConfigQRCode.app_id,
                AlipayConfigQRCode.merchant_private_key, "json",
                AlipayConfigQRCode.charset,
                AlipayConfigQRCode.alipay_public_key,
                AlipayConfigQRCode.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //这里设置支付后跳转的地址
        alipayRequest.setReturnUrl("http://localhost:8090/notify_url");
        //付款金额，必填

        String total_amount = totalPrice;
        //订单名称，必填

        String subject = "体检人名字："+name;

        //用于后面判断是否支付成功
        trade_noCheck=null;
        registerIdCheck=null;
        String id = UUID.randomUUID().toString();
        trade_noCheck = id;
        registerIdCheck = registerId;

        //订单编号
        String out_trade_no = id;
        //商品描述，可空
//        String body = "用户订购商品个数：" + bill.getTicketnum();
        String body = "处方号为："+prescriptionNum;
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "5m";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        AlipayConfigQRCode.logResult(result);// 记录支付日志
        response.setContentType("text/html; charset=gbk");
        PrintWriter out = response.getWriter();
        out.print(result);

        return null;
    }

    @RequestMapping("/notify_url")
    public String Notify(HttpServletRequest request,HttpSession session) throws Exception {
        System.out.println("----------------------------notify_url------------------------");
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");

        if(out_trade_no.equals(trade_noCheck)){
            medicalExaminationService.MoneyToPayExam(registerIdCheck,session);
        }
        return "toll/examinationToll";
    }

    @RequestMapping("/notify_url2")
    public String notify_url2(HttpServletRequest request,HttpSession session) throws Exception {
        System.out.println("----------------------------notify_url------------------------");
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");

        if(out_trade_no.equals(trade_noCheck)){
            payService.MoneyPay(cardId1, prescriptionNum1, session);
        }
        return "toll/outpatientToll";
    }


    //挂号的支付宝支付
    @RequestMapping("/AlipayToPayReg")
    @ResponseBody
    public String AlipayToPayReg(String cardId,String name,String total, HttpServletResponse response) throws AlipayApiException, IOException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigQRCode.gatewayUrl,
                AlipayConfigQRCode.app_id,
                AlipayConfigQRCode.merchant_private_key, "json",
                AlipayConfigQRCode.charset,
                AlipayConfigQRCode.alipay_public_key,
                AlipayConfigQRCode.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //这里设置支付后跳转的地址
        alipayRequest.setReturnUrl("http://localhost:8090/notify_url3");
        //付款金额，必填

        String total_amount = total;
        //订单名称，必填

        String subject = "卡号："+cardId;

        //用于后面判断是否支付成功
        trade_noCheck=null;
        String id = UUID.randomUUID().toString();
        trade_noCheck = id;

        //订单编号
        String out_trade_no = id;
        //商品描述，可空
//        String body = "用户订购商品个数：" + bill.getTicketnum();
        String body = "病人："+name;
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "5m";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        AlipayConfigQRCode.logResult(result);// 记录支付日志
        response.setContentType("text/html; charset=gbk");
        PrintWriter out = response.getWriter();
        out.print(result);

        return null;
    }

    @RequestMapping("/notify_url3")
    public String notify_url3(HttpServletRequest request,HttpSession session) throws Exception {
        System.out.println("----------------------------notify_url------------------------");
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");

        if(out_trade_no.equals(trade_noCheck)){
            return "register/register";
        }
        return null;
    }
}
